package com.yjd.back.contentmanager;

import com.alibaba.fastjson.JSON;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.IntroDetailModel;
import com.yjd.comm.base.model.PagerHtmlModel;
import com.yjd.comm.base.service.IIntroDetailService;
import com.yjd.comm.doctor.model.DoctorModel;
import com.yjd.comm.doctor.service.IDoctorService;
import com.yjd.comm.enums.ReferenceTypeEnum;
import com.yjd.comm.fs.util.FileUtil;
import com.yjd.comm.org.model.OrganizationModel;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.project.model.PrjCategoryModel;
import com.yjd.comm.project.model.ProjectModel;
import com.yjd.comm.project.model.ProjectRateConfig;
import com.yjd.comm.project.model.ProjectRateModel;
import com.yjd.comm.project.service.IPrjCategoryService;
import com.yjd.comm.project.service.IProjectService;
import com.yjd.comm.resource.model.ResourceModel;
import com.yjd.comm.system.dto.AdminDataWrap;
import com.yjd.comm.system.util.AdminDataUtil;
import com.yjd.comm.tag.service.ITagService;
import com.yjd.comm.util.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.util.*;

/**
 * 后台项目相关操作
 * Created by yangchangyan on 2017/7/10.
 */
@Controller("com.yjd.back.contentmanager.ProjectControl")
@Scope("prototype")
@RequestMapping("/project")
public class ProjectControl extends BaseControl {

    @Resource
    private IProjectService projectService;

    @Resource
    private IOrganizationService organizationService;

    @Resource
    private IDoctorService doctorService;

    @Resource
    private IIntroDetailService introDetailService;

    @Resource
    private IPrjCategoryService prjCategoryService;

    @Resource
    private ITagService tagService;

    /**
     * 查询所有项目，分页查询
     * @return void
     * @throws
     */
    @RequestMapping(value = "/all")
    public String allProject() throws Exception {

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("sort", "create_time desc");
        paramMap.put("rows", "20");
        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                this.projectService.getPageModel(paramMap, DbWREnums.READ), paramMap,
                ServletUtil.getUrl("/project/all"));

        OrganizationModel org = null;
        ProjectModel project = null;
        DoctorModel doctor = null;
        for(Object obj: pager.getPagerModel().getDataList()){
            project = (ProjectModel)obj;
            org = organizationService.getModelById(project.getOrg_id(), DbWREnums.READ);
            project.getStrMap().put("org_name", null == org ? "" : org.getOrg_name());

            doctor = doctorService.getModelById(project.getDoctor_id(), DbWREnums.READ);
            project.getStrMap().put("doctor_name", null == doctor ? "" : doctor.getName());

            project.getStrMap().put("create_time", DateUtil.timestampToDateString(project.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            project.getStrMap().put("last_update_time", DateUtil.timestampToDateString(project.getLast_update_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
        }

        request.setAttribute("maps", paramMap);
        request.setAttribute("pager", pager);
        return "project.list";
    }

    /**
     * 发布新项目编辑页面
     * @return void
     * @throws
     */
    @RequestMapping(value = "/add")
    public String addProjectPage() throws Exception {
        request.setAttribute("projectCgy", projectCategory());
        Map<Long, String> orgAndName = organizationService.allOrgAndName();
        Map<Long, String> doctorAndName = Collections.EMPTY_MAP;
        for(Long org_id : orgAndName.keySet()){
            doctorAndName = doctorService.queryDoctorName(org_id);
            // 预先加载第一个机构的医生
            break;
        }
        request.setAttribute("orgids", orgAndName);
        request.setAttribute("doctorAndName", doctorAndName);
        request.setAttribute("tagModelList", tagService.queryTags(null, ReferenceTypeEnum.PROJECT));
        return "project.add";
    }

    /**
     * 编辑页面
     * @return void
     * @throws
     */
    @RequestMapping(value = "/edit")
    public String editProjectPage(Long id) throws Exception {
        ProjectModel pm = projectService.getModelById(id, DbWREnums.READ);
        if(StringUtil.isNotEmpty(pm.getProject_pic())){
            request.setAttribute("project_pic", ServletUtil.getFileUrl(pm.getProject_pic()));
        }
        IntroDetailModel idm = introDetailService.getModelById(pm.getDetail_id(), DbWREnums.READ);
        if(null != idm){
            pm.getStrMap().put("detail", idm.getContent());
        }
        AdminDataWrap loginAdmin = AdminDataUtil.getAdminDataWrap(request,
                response);
        String sign = DigestUtils.md5Hex(loginAdmin.getAdminModel()
                .getPassword() + loginAdmin.getAdminModel().getAdmin_id());

        // 获取对应机构的最新期数配置情况
        OrganizationModel org = organizationService.getModelById(pm.getOrg_id(), DbWREnums.READ);
        List<Integer> periodsList = Collections.EMPTY_LIST;
        if(null == org){
            periodsList  = StagesInterestUtils.getMfqPeriodsConfig();
        } else {
            periodsList  = StringUtil.getObject(org.getLimit_config(), List.class);
        }

        //如果设置了个性化利率时显示设置情况
        if(StringUtil.isNotEmpty(pm.getRate_config())){
            Map rateMap = StringUtil.getObject(pm.getRate_config(),HashMap.class);
            List<ProjectRateModel> projectRateModels = new ArrayList<ProjectRateModel>();
            for(Integer period : periodsList){
                if(rateMap.containsKey(period.toString())){
                    projectRateModels.add(new ProjectRateModel(period, Double.parseDouble(rateMap.get(period.toString()).toString())));
                }else{
                    projectRateModels.add(new ProjectRateModel(period, 0.0D));
                }
            }
            request.setAttribute("rateList",projectRateModels);
        }

        request.setAttribute("tagModelList",tagService.queryTags(id, ReferenceTypeEnum.PROJECT));
        request.setAttribute("project", pm);
        request.setAttribute("sign", sign);
        request.setAttribute("uid", loginAdmin.getAdminModel().getAdmin_id());
        request.setAttribute("projectCgy", projectCategory());
        request.setAttribute("orgids", organizationService.allOrgAndName());
        request.setAttribute("doctorAndName", doctorService.queryDoctorName(pm.getOrg_id()));

        return "project.add";
    }

    /**
     * 发布新项目
     * @return void
     * @throws
     */
    @RequestMapping(value = "/add/submit")
    public void addDoctor(MultipartHttpServletRequest multipartRequest, ProjectModel pm) throws Exception {
        if(StringUtil.isEmpty(pm.getProject_name())){
            FrameUtil.throwBaseException1("项目名不能为空");
        }

        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);

        // 上传项目图片
        ResourceModel res = new ResourceModel();
        res.setRef_type(ReferenceTypeEnum.PROJECT.getCode());
        res.setRef_id(pm.getProject_id());
        String image_path = FileUtil.uploadFileToRemote(multipartRequest.getFileMap(), ReferenceTypeEnum.PROJECT, res);
        if(StringUtil.isNotEmpty(image_path)){
            pm.setProject_pic(image_path);
        }

        projectService.createOrUpdate(pm, (String)paramMap.get("detail"), request.getParameterValues("tags"));

        super.successMsg(ServletUtil.getUrl("/project/all"), "保存项目成功");
    }

    /**
     * 删除项目
     * @return void
     * @throws
     */
    @RequestMapping(value = "/delete")
    public void deleteProject(Long id) throws Exception {
        ProjectModel project = this.projectService.getModelById(id, DbWREnums.READ);
        if(null == project){
            FrameUtil.throwBaseException1("项目不存在");
        }

        introDetailService.delete(project.getDetail_id());
        projectService.delete(project.getProject_id());

        this.successMsg("删除项目成功");
    }

    /**
     * 项目利率配置
     * @return void
     * @throws
     */
    @RequestMapping(value = "/editRate")
    public String editRate(Long id) throws Exception {
        ProjectModel project = this.projectService.getModelById(id, DbWREnums.READ);
        if(null == project){
            FrameUtil.throwBaseException1("项目不存在");
        }

        // 获取对应机构的最新期数配置情况
        OrganizationModel org = organizationService.getModelById(project.getOrg_id(), DbWREnums.READ);
        List<Integer> periodsList = Collections.EMPTY_LIST;
        if(null == org){
            periodsList  = StagesInterestUtils.getMfqPeriodsConfig();
        } else {
            periodsList  = StringUtil.getObject(org.getLimit_config(), List.class);
        }

        // 获取项目配置的利率情况
        Map rateMap = null;
        if(StringUtil.isNotEmpty(project.getRate_config())){
            rateMap =  StringUtil.getObject(project.getRate_config(),HashMap.class);
        }

        List<ProjectRateModel> rateList = new ArrayList<ProjectRateModel>();
        for(Integer periods : periodsList){
            Double rate = 0D;
            if(rateMap!=null){
               Object obj =  rateMap.get(periods.toString());
                if(obj!=null){
                    rate = Double.parseDouble(obj.toString());
                }
            }
            rateList.add(new ProjectRateModel(Integer.parseInt(periods.toString()),rate));
        }

        request.setAttribute("project_name",project.getProject_name());
        request.setAttribute("project_id",id);
        request.setAttribute("periodsList",rateList);
        return "project.editRate";
    }

    /**
     * 项目利率配置保存
     * @return void
     * @throws
     */
    @RequestMapping(value = "/rateSave")
    public void rateSave(ProjectRateConfig config,Long prject_id) throws Exception {
        if(config==null||prject_id==null){
            FrameUtil.throwBaseException1("参数不能为空");
        }

        ProjectModel project = this.projectService.getModelById(prject_id, DbWREnums.READ);
        if(null == project){
            FrameUtil.throwBaseException1("项目不存在");
        }

        List<ProjectRateModel> rateList = config.getRateList();
        Map rateMap = new HashMap();
       for (ProjectRateModel model:rateList){
           if(model.getRate()==null||model.getRate().intValue()==0){
               FrameUtil.throwBaseException1("请配置"+model.getLimit()+"期数利率");
           }
           rateMap.put(model.getLimit().toString(),model.getRate().toString());
       }
        this.projectService.updateByMap(FrameUtil.newHashMap("project_id",prject_id,"rate_config", JSON.toJSONString(rateMap),
                "last_update_time",FrameUtil.getTime(null)));
        super.successMsg(ServletUtil.getUrl("/project/all"), "利率配置成功");
    }

    /**
     * 开启项目
     * @return void
     * @throws
     */
    @RequestMapping(value = "/open")
    public void openProject(Long id) throws Exception {
        changeProjectIsUsed(id,1);
        this.successMsg("开启项目成功");
    }

    /**
     *禁用项目
     * @return void
     * @throws
     */
    @RequestMapping(value = "/close")
    public void closeProject(Long id) throws Exception {
        changeProjectIsUsed(id,0);
        this.successMsg("禁用项目成功");
    }

    private void changeProjectIsUsed(Long id,Integer isUsed)throws Exception{
        if(id==null||isUsed==null){
            FrameUtil.throwBaseException1("参数不能为空");
        }
        ProjectModel project = this.projectService.getModelById(id, DbWREnums.READ);
        if(null == project){
            FrameUtil.throwBaseException1("项目不存在");
        }
        projectService.updateByMap(FrameUtil.newHashMap("project_id",id,"is_used",isUsed));
    }

    @RequestMapping("/org/doctor")
    public void queryDoctorNameAnd(Long org_id) throws Exception {
        Map<String, Object> paramMap = ServletUtil.getParameterMap(request);
        paramMap.put("doctorAndName", doctorService.queryDoctorName(org_id));
        this.successData(paramMap);
    }

    private Map<String,Object> projectCategory() throws Exception {
        List<PrjCategoryModel> projectCgy =  prjCategoryService.getModelList(null,DbWREnums.READ);
        Map<String,Object> cgys = new HashMap<String,Object>();
        for(PrjCategoryModel pcm : projectCgy){
            cgys.put(pcm.getId().toString(), pcm.getName());
        }
        return cgys;
    }
}
